<?php
namespace Admin\Model;
use Think\Model;
/**
 * 内容模型
 */
 class DefaultonmodelModel extends  Model{
 	
 	protected $tableName = 'defaultonmodel'; 
	
	protected $_validate = array();//申明空自动验证
	
	protected $_auto = array ();//申明自动完成
	
	/**
	 * 添加内容
	 */
	public function addContent($selfTable,$mid){
		header("Content-type:text/html;charset=utf-8");
		//自动验证
		$this->_validate = array(
			array('cid','require','栏目不能为空'),
			array('atitle','require','标题不能为空'),
			array('content','require','内容字段不建议留空'),
		);
		if(!$this->create()){
			return false;
		}
		
//		if($_FILES['ipic']['error'][0] != 4){
//			//上传图像
//			$upload = new \Think\Upload();// 实例化上传类
//			$upload->maxSize   =     3145728 ;// 设置附件上传大小
//			$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
//			$upload->savePath  =     'model_images/big/'; // 设置附件上传目录
//			$upload->saveName  =    'duosute_'.date('ymdHis');
//			$upload->autoSub   = 	true;
//			$upload->callback  =    false;
//			$upload->subName   =    false;
//			$file =  $upload->upload();
//			if(!$file) {// 上传错误提示错误信息        
//				$this->error='上传错误';
//				return false;
//		    }else{
//				//缩图
//				foreach($file as $k =>$v){
//					$path =  'Uploads/'.$file[$k]['savepath'].$file[$k]['savename'];//原图样式  大图样式
//					$thumbPath = 'Uploads/'.$file[$k]['savepath'].'thumb/100X100_'.$file[$k]['savepath']; 	//如果批量上传 	$file[0]['savepath'] 加0	
//					$thumbPath= str_replace('big/', '', $thumbPath); //组合路径   缩图图路径样式  Uploads/model_images/thumb/100X100_duosute_150812155815.png
//					$img =  new \Think\Image();
//					$img->open($path);
//					$img->thumb(100, 100,\Think\Image::IMAGE_THUMB_FIXED)->save($thumbPath);
//					$imglist[] = $file[$k]['savename'];				//将文件名插入数组
//				}
//				$data['athum'] = $imglist[0];//文章缩图图
//				$data['ipic'] = implode(',', $imglist);//图集
//		    }	
//		};

		//上传软件
		if($_FILES['sdownurl']['error'] != 4 && isset($_POST['sdownurl'])){
			//上传图像
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =     3145728 ;// 设置附件上传大小
			$upload->exts      =     array('exe', 'zip', 'rar', 'iso','igz','apk','jpg','png','gif');// 设置附件上传类型
			$upload->savePath  =     'soft/'.date('y_m_d').'/'; // 设置附件上传目录
			$upload->saveName  =    'duosute_'.date('ymdHis');
			$upload->autoSub   = 	true;
			$upload->callback  =    false;
			$upload->subName   =    false;
			$file =  $upload->upload();
			if(!$file) {// 上传错误提示错误信息        
				$this->error='上传错误';
				return false;
		    }else{
				$data['sdownurl'] =$file['sdownurl']['savepath'].$file['sdownurl']['savename'] ;
		    }	
		};
			$this->tableName = $selfTable;
			
			//要插入表名 
			//$tableName = $modelField['mmodel_name'] == 'articleonmodel'? :$modelField['mmodel_name'];
			//组合数据
			$datakey = array_keys($_POST);			//取出psot的所有键名
			foreach($datakey as $k => $v){			//循环键名
				if(is_array($_POST[$v])){			//如果post对应值是数组 就转字符串
					$data[$v] = implode(',', $_POST[$v]);
				}else{
					$data[$v] =  $_POST[$v];//字符串直接赋值
				}
			}
			//补加字段
			$data['cid'] 		= I('get.cid');			//栏目cid 
			$data['amodel_id'] 	= $mid;			//栏目cid 
			$data['aauthor'] 	= session('uid'); 		//发布者id
			$data['aip']    	= get_client_ip();		//发布者ip
			$data['aaddtime']   = time();
			$data['aedittime']  = $data['aaddtime'];
			
			$data['aclick']  = $data['aclick'] == ''?mt_rand(0, 500):$data['aclick'];
			//添加缩略图  截取一张做缩略图
			$athum = ltrim($data['ipic'],',');
			$newthum = strpos($athum,',');
			if($newthum){
				$data['athum']  = substr($athum,0,$newthum);
			}else{
				$data['athum']  = $athum;
			}
			//文章摘要			
			$data['adigest']  = $data['adigest'] != ""?$data['adigest']:mb_substr($data['content'] , 0,150);
		
			
			//查询tag表名 判断重复性
			$tagData = M('tag')->field('tname,tid')->select(); 
			//多维转一维
			foreach($tagData as $kk => $vv){
				$tid[] = $vv['tid'];
				$tname[] = $vv['tname'];
			}
			$tidData =array_combine($tname,$tid);		//键名键值重组 
			//tag标签表 组合写入数据库
			$data['content_rule'] = str_ireplace(array('，','|','。','/'), ',', $data['content_rule'] ); //字符过滤替换  将中文符号转英文符号
			if($data['content_rule'] != ''){
				$tag = array_unique(array_filter(explode(',', $data['content_rule'])));   //字符串转数组 -> 去空 ->  去重
				//tag标签名重复性验证				
				foreach($tag as $k => $v){
						if(in_array($v, $tname)){
							$newtag[$k] = $tidData[$v];		//通过重铸后的键名来找键值
						}else{										//如果不存在 创建 返回tid 组合写入关联表
							$newTagName['tname'] = $v;
							$newtag[$k] = M('tag')->add($newTagName);
						}
					}
			};
			//文章摘要过滤html标签  	
			$data['adigest'] = strip_tags($data['adigest']);
			$data['adigest'] = str_replace(array('&nbsp;',"\r"), '', $data['adigest']);			//取出空格符
			//描文本 文章内容描文本替换
			if(isset($data['content'])){
				$href = M('href')->select();
				$replaceStr = '';
				foreach($href as $k=>$v){
					$replaceTitle = $v['title'];
					$replaceStr .= "<a href=".$v['url']." target='_blank'>".$v['title']."</a>" .",";
				}
				$data['content'] = str_replace($replaceTitle, $replaceStr, $data['content']);
			}
			//默认文章表写入数据 标题、热门相关属性、发布时间、发布人相关信息
			$aid = M("defaultonmodel")->add($data); 
			$data['aid'] = $aid;
			//模型独立表
			M($this->tableName)->add($data);
			//如果tag标签不为空已设置就写入
			
			if(isset($tag)){
				//写入数据库
				foreach($tag as $k => $v){
					//组合tag表信息写入
					$data['tagid'] 					= $newtag[$k];
					$data['duosute_article_aid'] 	= $aid;
					$data['duosute_category_cid']   = I('get.cid');
				    //写入tag表
					M('tagarticle')->add($data);
				}
			}
			return true;
	}

	/**
	 * 修改内容
	 */
	public function editContent($selfTable,$mid){
		header("Content-type:text/html;charset=utf-8");
		$aid = I('get.aid');
		//自动验证
		$this->_validate = array(
			array('atitle','require','标题不能为空'),
			array('content','require','内容字段不建议留空'),
		);
		if(!$this->create()){
			return false;
		}
		//上传软件
		if($_FILES['sdownurl']['error'] != 4 && isset($_POST['sdownurl'])){
			//上传图像
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =     3145728 ;// 设置附件上传大小
			$upload->exts      =     array('exe', 'zip', 'rar', 'iso','igz','apk','jpg','png','gif');// 设置附件上传类型
			$upload->savePath  =     'soft/'.date('y_m_d').'/'; // 设置附件上传目录
			$upload->saveName  =    'duosute_'.date('ymdHis');
			$upload->autoSub   = 	true;
			$upload->callback  =    false;
			$upload->subName   =    false;
			$file =  $upload->upload();
			if(!$file) {// 上传错误提示错误信息        
				$this->error='上传错误';
				return false;
		    }else{
				$data['sdownurl'] =$file['sdownurl']['savepath'].$file['sdownurl']['savename'] ;
		    }	
		};
			$this->tableName = $selfTable;
			//要插入表名 
			//$tableName = $modelField['mmodel_name'] == 'articleonmodel'? :$modelField['mmodel_name'];
			//组合数据
			$datakey = array_keys($_POST);			//取出psot的所有键名
			foreach($datakey as $k => $v){			//循环键名
				if(is_array($_POST[$v])){			//如果post对应值是数组 就转字符串
					$data[$v] = implode(',', $_POST[$v]);
				}else{
					$data[$v] =  $_POST[$v];//字符串直接赋值
				}
			}
			//补加字段
			$data['cid'] 		= I('get.cid');			//栏目cid 
			$data['amodel_id'] 	= $mid;					//模型id 
			$data['aauthor'] 	= session('uid'); 		//发布者id
			$data['aip']    	= get_client_ip();		//发布者ip
			$data['aaddtime']   = time();
			$data['aedittime']  = $data['aaddtime'];
			
			$data['aclick']  = $data['aclick'] == ''?mt_rand(0, 500):$data['aclick'];
			//添加缩略图  截取一张做缩略图
			$athum = ltrim($data['ipic'],',');
			$newthum = strpos($athum,',');
			if($newthum){
				$data['athum']  = substr($athum,0,$newthum);
			}else{
				$data['athum']  = $athum;
			}
			//文章摘要			
			$data['adigest']  = $data['adigest'] != ""?$data['adigest']:mb_substr($data['content'] , 0,150);
			
			//删除旧标签
			M('tagarticle')->where("duosute_article_aid ='{$aid}'")->delete();
			//查询tag表名 判断重复性
			//查询tag表名 判断重复性
			$tagData = M('tag')->field('tname,tid')->select(); 
			//多维转一维
			foreach($tagData as $kk => $vv){
				$tid[] = $vv['tid'];
				$tname[] = $vv['tname'];
			}
			$tidData =array_combine($tname,$tid);		//键名键值重组 
			//tag标签表 组合写入数据库
			$data['content_rule'] = str_ireplace(array('，','|','。','/'), ',', $data['content_rule'] ); //字符过滤替换  将中文符号转英文符号
			if($data['content_rule'] != ''){
				$tag = array_unique(array_filter(explode(',', $data['content_rule'])));   //字符串转数组 -> 去空 ->  去重
				//tag标签名重复性验证				
				foreach($tag as $k => $v){
						if(in_array($v, $tname)){
							$newtag[$k] = $tidData[$v];		//通过重铸后的键名来找键值
						}else{										//如果不存在 创建 返回tid 组合写入关联表
							$newTagName['tname'] = $v;
							$newtag[$k] = M('tag')->add($newTagName);
						}
					}
			};
			//文章摘要过滤html标签
			$data['adigest'] = strip_tags($data['adigest']);
			
			//默认文章表写入数据 标题、热门相关属性、发布时间、发布人相关信息
			M("defaultonmodel")->where("id='{$aid}'")->save($data); 
			
			$data['aid'] = $aid;			
			//模型独立表
			M($this->tableName)->where("aid='{$aid}'")->save($data);
			//如果tag标签不为空已设置就写入
			
			if(isset($tag)){
				//写入数据库
				foreach($tag as $k => $v){
					//组合tag表信息写入
					$data['tagid'] 					= $newtag[$k];
					$data['duosute_article_aid'] 	= $aid;
					$data['duosute_category_cid']   = I('get.cid');
				    //写入tag表
					M('tagarticle')->add($data);
				}
			}

			return true;
	}

	/**
	 * 删除文章
	 */
	 public function delContent(){
	 	$aid = I("get.aid");
		$cid = I('get.cid');
		//通过cid查询栏目 模型表  删除表里面的文章信息
		$modelField = M('category')->JOIN("duosute_model on duosute_category.duosute_model_mid = duosute_model.mid")->where("cid = '{$cid}'")->field('mmodel_name')->getField('mmodel_name');

		if($modelField != ''){			
			M($modelField)->where("aid='{$aid}'")->delete();
		}
		//删除默认表文章
		M('defaultonmodel')->where("id='{$aid}'")->delete();
		//查询tag表删除内容
		M('tagarticle')->where("duosute_article_aid='{$aid}'")->delete();
		return true;
	 }

 }
